import { defineStore } from "pinia";
import { LocalStorage } from "quasar";
import { SessionStorage } from "quasar";
import {
  addUniversoUzanto,
  login_query,
  logout_query,
} from "src/queries/mutations";
import { listOrganizaiton, mi } from "src/queries/queries";

import { apollo } from "src/boot/apollo";
import { debugLog } from "src/utils";

export const useAuthStore = defineStore("auth", {
  state: () => {
    return {
      jwt: null,
      user: null,
      isLoggedIn: null,
      konfirmita: null,
      isAdmin: null,
      authtoken: null,
      csrftoken: null,
      organizations: null,
      authData: null,
    };
  },
  getters: {
    getJWTpayload: (state) => {
      if (state.jwt) {
        const jwt = state.jwt;
        const arr = jwt.split(".");
        return arr.map((part) => {
          try {
            return JSON.parse(atob(part));
          } catch {
            return part;
          }
        });
      } else return [];
    },
    getJWTisExpired: (state) => {
      if (state.getJWTpayload.length > 0) {
        if (state.getJWTpayload[1].exp) {
          const date = new Date();
          const jwt_date = new Date(state.getJWTpayload[1].exp * 1000);
          // console.log(jwt_date, " - ", date);
          return jwt_date - date;
        }
      } else return -1;
    },
    getUserName: (state) => {
      return (
        state.user?.universoUzanto?.retnomo ||
        state.user?.unuaNomo?.enhavo ||
        state.user?.duaNomo?.enhavo ||
        state.user?.familinomo?.enhavo ||
        state.user?.chefaRetposhto ||
        null
      );
    },
    getUserEmail: (state) => {
      return state.user?.chefaRetposhto || null;
    },
    getMyOrganizations: (state) => {
      if (state.organizations && Array.isArray(state.organizations.edges)) {
        return state.organizations.edges.map((item) => item.node.uuid);
      } else return [];
    },
    getAuthData: (state) => {
      return {
        user: state.user,
        isLoggedIn: state.isLoggedIn,
        konfirmita: state.konfirmita,
        isAdmin: state.isAdmin,
      };
    },
  },
  actions: {
    setAvataro(payload) {
      console.log(payload);
      console.log(this.user.avataro);
      this.user.avataro.bildoE.url = payload.bildoE.url;
      this.user.avataro.bildoF.url = payload.bildoF.url;
    },
    getLocalStorage() {
      let jwt_token = null;
      let csrf_token = null;
      let auth_token = null;
      if (SessionStorage.has("jwt_token")) {
        jwt_token = SessionStorage.getItem("jwt_token");
      }
      if (SessionStorage.has("csrf_token")) {
        csrf_token = SessionStorage.getItem("csrf_token");
      }
      if (SessionStorage.has("auth_token")) {
        auth_token = SessionStorage.getItem("auth_token");
      }
      if (LocalStorage.has("jwt_token")) {
        jwt_token = LocalStorage.getItem("jwt_token");
      }
      if (LocalStorage.has("csrf_token")) {
        csrf_token = LocalStorage.getItem("csrf_token");
      }
      if (LocalStorage.has("auth_token")) {
        auth_token = LocalStorage.getItem("auth_token");
      }
      this.jwt = jwt_token;
      this.csrftoken = csrf_token;
      this.authtoken = auth_token;
      debugLog("jwt: ", jwt_token);
      debugLog("csrf: ", csrf_token);
      debugLog("auth: ", auth_token);
      if (this.getJWTisExpired < 0) {
        this.isLoggedIn = false;
        this.clearLocalStorage();
        return Promise.reject();
      }

      if (jwt_token && csrf_token && auth_token) {
        return Promise.resolve();
      } else {
        this.isLoggedIn = false;
        return Promise.reject();
      }
    },
    setLocalStorage(save) {
      if (save) {
        LocalStorage.set("jwt_token", this.jwt);
        LocalStorage.set("csrf_token", this.csrftoken);
        LocalStorage.set("auth_token", this.authtoken);
      } else {
        SessionStorage.set("jwt_token", this.jwt);
        SessionStorage.set("csrf_token", this.csrftoken);
        SessionStorage.set("auth_token", this.authtoken);
      }
    },
    clearLocalStorage() {
      LocalStorage.remove("jwt_token");
      LocalStorage.remove("csrf_token");
      LocalStorage.remove("auth_token");
      SessionStorage.remove("jwt_token");
      SessionStorage.remove("csrf_token");
      SessionStorage.remove("auth_token");
    },
    async login(login, password, save = true) {
      try {
        const { loading, error, data } = await apollo.registrado.mutate({
          mutation: login_query,
          variables: { login: login, password: password },
        });
        if (data.ensaluti.status) {
          this.jwt = data.ensaluti.jwtToken;
          this.authtoken = data.ensaluti.token;
          this.csrftoken = data.ensaluti.csrfToken;

          this.setLocalStorage(save);
          return Promise.resolve(data.ensaluti);
        } else {
          this.konfirmita = data.ensaluti.konfirmita;
          return Promise.reject(data.ensaluti);
        }
      } catch (err) {
        return Promise.reject(err);
      }
    },
    async logout() {
      try {
        const response = await apollo.registrado.mutate({
          mutation: logout_query,
        });
        if (response.data.elsaluti.status) {
          this.$reset();
          this.isLoggedIn = false;
          this.clearLocalStorage();
          return Promise.resolve(response.data.elsaluti);
        }
        return Promise.reject(response.data.elsaluti);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    async getMe() {
      debugLog("get me");
      try {
        const response = await apollo.registrado.query({
          query: mi,
          errorPolicy: "all",
          fetchPolicy: "network-only",
        });
        debugLog("response: ", response);
        const resp = response.data.mi;
        if (resp) {
          this.user = resp;
          this.isAdmin = resp.isAdmin;
          this.isLoggedIn = true;
          this.konfirmita = resp.konfirmita;
          return Promise.resolve(resp);
        }
        this.$reset();
        this.isLoggedIn = false;

        this.clearLocalStorage();
        return Promise.resolve(response);
      } catch (err) {
        return Promise.reject(err);
      }
    },

    fetchOrganizations(payload) {
      return apollo.default
        .query({
          query: listOrganizaiton,
          variables: payload,
          errorPolicy: "all",
          fetchPolicy: "network-only",
        })
        .then((data) => {
          const organizations = data.data.organizo;
          this.organizations = organizations;
          // return Promise.resolve(organizations);
        })
        .catch((error) => Promise.reject(error));
    },
    addUniversoUzanto(vars) {
      return apollo.default
        .mutate({
          mutation: addUniversoUzanto,
          variables: vars,
        })
        .then((data) => {
          const resp = data.data.redaktuProfilo;
          this.getMe();
          return Promise.resolve(resp);
        })
        .catch((err) => {
          // console.error(err);
          // Ошибка запроса на уровне сети/протокола
          return Promise.reject(err);
        });
    },
  },
});
